/**
 * amis v6.13.0
 * build time: 2025-08-12
 * Copyright 2018-2025 baidu
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _AutoFoldedList = require('amis-ui/lib/components/AutoFoldedList');
var _Html = require('amis-ui/lib/components/Html');
var _Button = require('amis-ui/lib/components/Button');
var _Icon = require('amis-ui/lib/components/Icon');
var _Spinner = require('amis-ui/lib/components/Spinner');
var _Select = require('amis-ui/lib/components/Select');
var _confirm = require('amis-ui/lib/components/Alert');
var tslib = require('tslib');
var React = require('react');
var isEqual = require('lodash/isEqual');
var pickBy = require('lodash/pickBy');
var omitBy = require('lodash/omitBy');
var partition = require('lodash/partition');
var amisCore = require('amis-core');
var pick = require('lodash/pick');
var ReactDOM = require('react-dom');
var omit = require('lodash/omit');
var find = require('lodash/find');
var mobxStateTree = require('mobx-state-tree');
var isPlainObject = require('lodash/isPlainObject');
var memoize = require('lodash/memoize');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _AutoFoldedList__default = /*#__PURE__*/_interopDefaultLegacy(_AutoFoldedList);
var _Html__default = /*#__PURE__*/_interopDefaultLegacy(_Html);
var _Button__default = /*#__PURE__*/_interopDefaultLegacy(_Button);
var _Icon__default = /*#__PURE__*/_interopDefaultLegacy(_Icon);
var _Spinner__default = /*#__PURE__*/_interopDefaultLegacy(_Spinner);
var _Select__default = /*#__PURE__*/_interopDefaultLegacy(_Select);
var _confirm__default = /*#__PURE__*/_interopDefaultLegacy(_confirm);
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var isEqual__default = /*#__PURE__*/_interopDefaultLegacy(isEqual);
var pickBy__default = /*#__PURE__*/_interopDefaultLegacy(pickBy);
var omitBy__default = /*#__PURE__*/_interopDefaultLegacy(omitBy);
var partition__default = /*#__PURE__*/_interopDefaultLegacy(partition);
var pick__default = /*#__PURE__*/_interopDefaultLegacy(pick);
var omit__default = /*#__PURE__*/_interopDefaultLegacy(omit);
var find__default = /*#__PURE__*/_interopDefaultLegacy(find);
var isPlainObject__default = /*#__PURE__*/_interopDefaultLegacy(isPlainObject);
var memoize__default = /*#__PURE__*/_interopDefaultLegacy(memoize);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
var _J$F_ = (__react_jsx__["default"] || __react_jsx__).Fragment;


;var INNER_EVENTS = ['selectedChange', 'columnSort', 'columnFilter', 'columnSearch', 'columnToggled', 'orderChange', 'rowClick', 'rowDbClick', 'rowMouseEnter', 'rowMouseLeave', 'selected'];
var CRUD = /** @class */function (_super) {
  tslib.__extends(CRUD, _super);
  function CRUD(props) {
    var _this = _super.call(this, props) || this;
    _this.filterOnEvent = memoize__default["default"](function (onEvent) {
      return omitBy__default["default"](onEvent, function (event, key) {
        return !INNER_EVENTS.includes(key);
      });
    });
    _this.controlRef = _this.controlRef.bind(_this);
    _this.handleFilterReset = _this.handleFilterReset.bind(_this);
    _this.handleFilterSubmit = _this.handleFilterSubmit.bind(_this);
    _this.handleFilterInit = _this.handleFilterInit.bind(_this);
    _this.handleAction = _this.handleAction.bind(_this);
    _this.dispatchEvent = _this.dispatchEvent.bind(_this);
    _this.handleBulkAction = _this.handleBulkAction.bind(_this);
    _this.handleChangePage = _this.handleChangePage.bind(_this);
    _this.handleBulkGo = _this.handleBulkGo.bind(_this);
    _this.handleDialogConfirm = _this.handleDialogConfirm.bind(_this);
    _this.handleDialogClose = _this.handleDialogClose.bind(_this);
    _this.handleItemChange = _this.handleItemChange.bind(_this);
    _this.handleSave = _this.handleSave.bind(_this);
    _this.handleSaveOrder = _this.handleSaveOrder.bind(_this);
    _this.handleSelect = _this.handleSelect.bind(_this);
    _this.handleChildPopOverOpen = _this.handleChildPopOverOpen.bind(_this);
    _this.handleChildPopOverClose = _this.handleChildPopOverClose.bind(_this);
    _this.search = _this.search.bind(_this);
    _this.silentSearch = _this.silentSearch.bind(_this);
    _this.handleQuery = _this.handleQuery.bind(_this);
    _this.renderHeaderToolbar = _this.renderHeaderToolbar.bind(_this);
    _this.renderFooterToolbar = _this.renderFooterToolbar.bind(_this);
    _this.clearSelection = _this.clearSelection.bind(_this);
    _this.filterItemIndex = _this.filterItemIndex.bind(_this);
    var location = props.location,
      store = props.store,
      pageField = props.pageField,
      perPageField = props.perPageField,
      totalField = props.totalField,
      syncLocation = props.syncLocation,
      loadDataOnce = props.loadDataOnce;
    var parseQueryOptions = _this.getParseQueryOptions(props);
    _this.mounted = true;
    if (syncLocation && location && (location.query || location.search)) {
      store.updateQuery(amisCore.parseQuery(location, parseQueryOptions), undefined, pageField, perPageField);
    } else if (syncLocation && !location && window.location.search) {
      store.updateQuery(amisCore.parseQuery(window.location, parseQueryOptions), undefined, pageField, perPageField);
    }
    _this.props.store.setFilterTogglable(!!_this.props.filterTogglable, _this.props.filterDefaultVisible);
    // 如果有 api，data 里面先写个 空数组，面得继承外层的 items
    // 比如 crud 打开一个弹框，里面也是个 crud，默认一开始其实显示
    // 的是外层 crud 的数据，等接口回来后就会变成新的。
    // 加上这个就是为了解决这种情况
    if (_this.props.api) {
      _this.props.store.updateData({
        items: []
      });
    }
    // 如果picker用visibleOn来控制显隐，显隐切换时，constructor => handleSelect => componentDidMount的执行顺序
    // 因此需要将componentDidMount中的设置选中项提前到constructor，否则handleSelect里拿不到的选中项
    var val;
    if (_this.props.pickerMode && (val = amisCore.getPropValue(_this.props))) {
      _this.syncSelectedFromPicker(val);
    }
    return _this;
  }
  CRUD.prototype.componentDidMount = function () {
    var _a = this.props,
      store = _a.store,
      autoGenerateFilter = _a.autoGenerateFilter,
      perPageField = _a.perPageField,
      columns = _a.columns;
    if (this.props.perPage && !store.query[perPageField || 'perPage']) {
      store.changePage(store.page, this.props.perPage);
    }
    // 没有 filter 或者 没有展示 filter 时应该默认初始化一次，
    // 否则就应该等待 filter 里面的表单初始化的时候才初始化
    // 另外autoGenerateFilter时，table 里面会单独处理这块逻辑
    // 所以这里应该忽略 autoGenerateFilter 情况
    if (!this.props.filter && !autoGenerateFilter || store.filterTogglable && !store.filterVisible) {
      this.handleFilterInit({});
    }
    this.parentContainer = this.getClosestParentContainer();
  };
  CRUD.prototype.componentDidUpdate = function (prevProps) {
    var _a;
    var props = this.props;
    var store = prevProps.store;
    if (amisCore.anyChanged(['toolbar', 'headerToolbar', 'footerToolbar', 'bulkActions'], prevProps, props)) {
      // 来点参数变化。
      this.renderHeaderToolbar = this.renderHeaderToolbar.bind(this);
      this.renderFooterToolbar = this.renderFooterToolbar.bind(this);
    }
    var val;
    if (this.props.pickerMode && !isEqual__default["default"](val = amisCore.getPropValue(this.props), amisCore.getPropValue(prevProps)) && !isEqual__default["default"](val, store.selectedItems.concat())) {
      /**
       * 更新链：Table -> CRUD -> Picker -> Form
       * 对于Picker模式来说，执行到这里的时候store.selectedItems已经更新过了，所以需要额外判断一下
       */
      this.syncSelectedFromPicker(val);
    }
    if (!!this.props.filterTogglable !== !!prevProps.filterTogglable) {
      store.setFilterTogglable(!!props.filterTogglable, props.filterDefaultVisible);
    }
    var dataInvalid = false;
    if (prevProps.syncLocation && prevProps.location && prevProps.location.search !== props.location.search) {
      // 同步地址栏，那么直接检测 query 是否变了，变了就重新拉数据
      store.updateQuery(amisCore.parseQuery(props.location, this.getParseQueryOptions(props)), undefined, props.pageField, props.perPageField);
      dataInvalid = !!(props.api && amisCore.isObjectShallowModified(store.query, this.lastQuery, false));
    }
    if (dataInvalid) {
      // 要同步数据
    } else if (prevProps.api && props.api && amisCore.isApiOutdated(prevProps.api, props.api, store.fetchCtxOf(prevProps.data, {
      pageField: prevProps.pageField,
      perPageField: prevProps.perPageField
    }), store.fetchCtxOf(props.data, {
      pageField: props.pageField,
      perPageField: props.perPageField
    }))) {
      dataInvalid = true;
    } else if (!props.api && amisCore.isPureVariable(props.source) && props.data !== prevProps.data) {
      var next = amisCore.resolveVariableAndFilter(props.source, props.data, '| raw');
      if (!this.lastData || this.lastData !== next) {
        store.initFromScope(props.data, props.source, {
          columns: (_a = store.columns) !== null && _a !== void 0 ? _a : props.columns,
          totalField: props.totalField
        });
        if (this.props.pickerMode && (val = amisCore.getPropValue(this.props))) {
          this.syncSelectedFromPicker(val);
        }
        this.lastData = next;
      }
    }
    if (dataInvalid) {
      this.search();
    }
  };
  CRUD.prototype.componentWillUnmount = function () {
    var _a, _b;
    this.mounted = false;
    clearTimeout(this.timer);
    (_b = (_a = this.filterOnEvent.cache).clear) === null || _b === void 0 ? void 0 : _b.call(_a);
  };
  CRUD.prototype.getParseQueryOptions = function (props) {
    var _a;
    var parsePrimitiveQuery = props.parsePrimitiveQuery;
    var normalizedOptions = {
      parsePrimitive: !!(amisCore.isObject(parsePrimitiveQuery) ? parsePrimitiveQuery === null || parsePrimitiveQuery === void 0 ? void 0 : parsePrimitiveQuery.enable : parsePrimitiveQuery),
      primitiveTypes: (_a = parsePrimitiveQuery === null || parsePrimitiveQuery === void 0 ? void 0 : parsePrimitiveQuery.types) !== null && _a !== void 0 ? _a : ['boolean']
    };
    return normalizedOptions;
  };
  /** 查找CRUD最近层级的父窗口 */
  CRUD.prototype.getClosestParentContainer = function () {
    var dom = ReactDOM.findDOMNode(this);
    var overlay = dom === null || dom === void 0 ? void 0 : dom.closest('[role=dialog]');
    return overlay;
  };
  CRUD.prototype.controlRef = function (control) {
    // 因为 control 有可能被 n 层 hoc 包裹。
    while (control && control.getWrappedInstance) {
      control = control.getWrappedInstance();
    }
    this.control = control;
  };
  CRUD.prototype.handleAction = function (e, action, ctx, throwErrors, delegate) {
    var _this = this;
    if (throwErrors === void 0) {
      throwErrors = false;
    }
    var _a = this.props,
      onAction = _a.onAction,
      store = _a.store,
      messages = _a.messages,
      pickerMode = _a.pickerMode,
      env = _a.env,
      pageField = _a.pageField,
      stopAutoRefreshWhenModalIsOpen = _a.stopAutoRefreshWhenModalIsOpen;
    if (store.loading) {
      //由于curd的loading样式未遮罩按钮部分，如果处于加载中时不处理操作
      return;
    }
    if (action.actionType === 'dialog') {
      store.setCurrentAction(action, this.props.resolveDefinitions);
      var idx_1 = ctx.index;
      var length_1 = store.items.length;
      stopAutoRefreshWhenModalIsOpen && clearTimeout(this.timer);
      return new Promise(function (resolve) {
        store.openDialog(ctx, {
          hasNext: idx_1 < length_1 - 1,
          nextIndex: idx_1 + 1,
          hasPrev: idx_1 > 0,
          prevIndex: idx_1 - 1,
          index: idx_1
        }, function (confirmed, value) {
          var _a;
          (_a = action.callback) === null || _a === void 0 ? void 0 : _a.call(action, confirmed, value);
          resolve({
            confirmed: confirmed,
            value: value
          });
        }, delegate || _this.context);
      });
    } else if (action.actionType === 'ajax') {
      store.setCurrentAction(action, this.props.resolveDefinitions);
      var data = ctx;
      // 由于 ajax 一段时间后再弹出，肯定被浏览器给阻止掉的，所以提前弹。
      var redirect = action.redirect && amisCore.filter(action.redirect, data);
      redirect && action.blank && env.jumpTo(redirect, action, data);
      // 如果 api 无效，或者不满足发送条件，则直接返回
      if (!amisCore.isEffectiveApi(action.api, data)) {
        return;
      }
      return store.saveRemote(action.api, data, {
        successMessage: action.messages && action.messages.success || messages && messages.saveSuccess,
        errorMessage: action.messages && action.messages.failed || messages && messages.saveFailed
      }).then(function (payload) {
        return tslib.__awaiter(_this, void 0, void 0, function () {
          var data, redirect;
          return tslib.__generator(this, function (_a) {
            switch (_a.label) {
              case 0:
                data = amisCore.createObject(ctx, payload);
                if (!(action.feedback && amisCore.isVisible(action.feedback, data))) return [3 /*break*/, 2];
                return [4 /*yield*/, this.openFeedback(action.feedback, data)];
              case 1:
                _a.sent();
                stopAutoRefreshWhenModalIsOpen && clearTimeout(this.timer);
                _a.label = 2;
              case 2:
                redirect = action.redirect && amisCore.filter(action.redirect, data);
                redirect && !action.blank && env.jumpTo(redirect, action, data);
                action.reload ? this.reloadTarget(amisCore.filterTarget(action.reload, data), data) : redirect ? null : this.search(undefined, undefined, true, true);
                action.close && this.closeTarget(action.close);
                return [2 /*return*/];
            }
          });
        });
      }).catch(function (e) {
        if (throwErrors || action.countDown) {
          throw e;
        }
      });
    } else if (action.actionType === 'reload' && !action.target) {
      this.reload();
    } else if (pickerMode && (action.actionType === 'confirm' || action.actionType === 'submit')) {
      store.setCurrentAction(action, this.props.resolveDefinitions);
      return Promise.resolve({
        items: store.selectedItems.concat()
      });
    } else if (action.onClick) {
      store.setCurrentAction(action, this.props.resolveDefinitions);
      var onClick = action.onClick;
      if (typeof onClick === 'string') {
        onClick = amisCore.str2function(onClick, 'event', 'props', 'data');
      }
      onClick && onClick(e, this.props, ctx);
    } else {
      onAction(e, action, ctx, throwErrors, delegate || this.context);
    }
  };
  CRUD.prototype.handleBulkAction = function (selectedItems, unSelectedItems, e, action) {
    var _this = this;
    var _a;
    var _b = this.props,
      store = _b.store,
      primaryField = _b.primaryField,
      onAction = _b.onAction,
      messages = _b.messages,
      pageField = _b.pageField,
      stopAutoRefreshWhenModalIsOpen = _b.stopAutoRefreshWhenModalIsOpen,
      env = _b.env;
    if (!selectedItems.length && action.requireSelected !== false) {
      return;
    }
    var ids = selectedItems.map(function (item) {
      return item.hasOwnProperty(primaryField) ? item[primaryField] : null;
    }).filter(function (item) {
      return item;
    }).join(',');
    var ctx = amisCore.createObjectFromChain([store.mergedData, {
      event: e // 固定事件数据从event.data中获取，方便批量操作按钮绑定动作时获取动作产生的数据
    }, tslib.__assign(tslib.__assign(tslib.__assign({}, selectedItems[0]), store.eventContext), {
      currentPageData: (((_a = store.mergedData) === null || _a === void 0 ? void 0 : _a.items) || []).concat(),
      rows: selectedItems,
      items: selectedItems,
      ids: ids
    })]);
    var fn = function () {
      if (action.actionType === 'dialog') {
        return _this.handleAction(e, tslib.__assign(tslib.__assign({}, action), {
          __from: 'bulkAction'
        }), ctx);
      } else if (action.actionType === 'ajax') {
        amisCore.isEffectiveApi(action.api, ctx) && store.saveRemote(action.api, ctx, {
          successMessage: action.messages && action.messages.success || messages && messages.saveSuccess,
          errorMessage: action.messages && action.messages.failed || messages && messages.saveFailed
        }).then(function (payload) {
          return tslib.__awaiter(_this, void 0, void 0, function () {
            var data, redirect;
            var _a;
            return tslib.__generator(this, function (_b) {
              switch (_b.label) {
                case 0:
                  data = amisCore.createObject(ctx, payload);
                  if (!(action.feedback && amisCore.isVisible(action.feedback, data))) return [3 /*break*/, 2];
                  return [4 /*yield*/, this.openFeedback(action.feedback, data)];
                case 1:
                  _b.sent();
                  stopAutoRefreshWhenModalIsOpen && clearTimeout(this.timer);
                  _b.label = 2;
                case 2:
                  action.reload ? this.reloadTarget(amisCore.filterTarget(action.reload, data), data) : this.search((_a = {}, _a[pageField || 'page'] = 1, _a), undefined, true, true);
                  action.close && this.closeTarget(action.close);
                  redirect = action.redirect && amisCore.filter(action.redirect, data);
                  redirect && env.jumpTo(redirect, action, data);
                  return [2 /*return*/];
              }
            });
          });
        }).catch(function () {
          return null;
        });
      } else if (onAction) {
        onAction(e, action, ctx, false, _this.context);
      }
    };
    // Action如果配了事件动作也会处理二次确认，这里需要处理一下忽略
    var confirmText = '';
    if (!action.ignoreConfirm && action.confirmText && env.confirm && (confirmText = amisCore.filter(action.confirmText, ctx))) {
      env.confirm(confirmText, amisCore.filter(action.confirmTitle, ctx) || undefined).then(function (confirmed) {
        return confirmed && fn();
      });
    } else {
      fn();
    }
  };
  CRUD.prototype.handleItemAction = function (action, ctx) {
    this.doAction(action, ctx);
  };
  CRUD.prototype.handleFilterInit = function (values) {
    var _a;
    var _b = this.props,
      defaultParams = _b.defaultParams,
      columns = _b.columns,
      matchFunc = _b.matchFunc,
      store = _b.store,
      orderBy = _b.orderBy,
      orderDir = _b.orderDir,
      totalField = _b.totalField,
      dispatchEvent = _b.dispatchEvent;
    var params = tslib.__assign({}, defaultParams);
    if (orderBy) {
      params['orderBy'] = orderBy;
      params['orderDir'] = orderDir || 'asc';
    }
    this.handleFilterSubmit(tslib.__assign(tslib.__assign(tslib.__assign({}, params), values), store.query), false, true, this.props.initFetch !== false, true);
    store.setPristineQuery();
    var _c = this.props,
      pickerMode = _c.pickerMode,
      options = _c.options;
    if (pickerMode) {
      store.initFromScope({
        items: options || []
      }, '${items}', {
        columns: (_a = store.columns) !== null && _a !== void 0 ? _a : columns,
        matchFunc: matchFunc,
        totalField: totalField
      });
      var val = void 0;
      if (val = amisCore.getPropValue(this.props)) {
        this.syncSelectedFromPicker(val);
      }
    }
  };
  CRUD.prototype.handleFilterReset = function (values, action) {
    var _a = this.props,
      store = _a.store,
      syncLocation = _a.syncLocation,
      env = _a.env,
      pageField = _a.pageField,
      perPageField = _a.perPageField;
    var resetQuery = {};
    Object.keys(values).forEach(function (key) {
      return resetQuery[key] = '';
    });
    store.updateQuery(tslib.__assign(tslib.__assign({}, resetQuery), store.pristineQuery), syncLocation && env && env.updateLocation ? function (location) {
      return env.updateLocation(location);
    } : undefined, pageField, perPageField, true);
    this.lastQuery = store.query;
    // 对于带 submit 的 reset(包括 actionType 为 reset-and-submit clear-and-submit 和 form 的 resetAfterSubmit 属性)
    // 不执行 search，否则会多次触发接口请求
    if ((action === null || action === void 0 ? void 0 : action.actionType) && ['reset-and-submit', 'clear-and-submit', 'submit'].includes(action.actionType)) {
      return;
    }
    this.search();
  };
  CRUD.prototype.handleFilterSubmit = function (values, jumpToFirstPage, replaceLocation, search, isInit) {
    var _a;
    var _b, _c;
    if (jumpToFirstPage === void 0) {
      jumpToFirstPage = true;
    }
    if (replaceLocation === void 0) {
      replaceLocation = false;
    }
    if (search === void 0) {
      search = true;
    }
    if (isInit === void 0) {
      isInit = false;
    }
    var _d = this.props,
      store = _d.store,
      syncLocation = _d.syncLocation,
      env = _d.env,
      pageField = _d.pageField,
      perPageField = _d.perPageField,
      loadDataOnceFetchOnFilter = _d.loadDataOnceFetchOnFilter,
      parsePrimitiveQuery = _d.parsePrimitiveQuery;
    var parseQueryOptions = this.getParseQueryOptions(this.props);
    /** 找出clearValueOnHidden的字段, 保证updateQuery时不会使用上次的保留值 */
    values = tslib.__assign(tslib.__assign({}, values), pickBy__default["default"]((_c = (_b = values === null || values === void 0 ? void 0 : values.__super) === null || _b === void 0 ? void 0 : _b.diff) !== null && _c !== void 0 ? _c : {}, function (value) {
      return value === undefined;
    }));
    values = syncLocation ? amisCore.qsparse(amisCore.qsstringify(values, undefined, true)) : values;
    /** 把布尔值反解出来 */
    if (parsePrimitiveQuery) {
      values = amisCore.parsePrimitiveQueryString(values, parseQueryOptions);
    }
    store.updateQuery(tslib.__assign(tslib.__assign({}, values), (_a = {}, _a[pageField || 'page'] = jumpToFirstPage ? 1 : store.page, _a)), syncLocation && env && env.updateLocation ? function (location) {
      return env.updateLocation(location, replaceLocation);
    } : undefined, pageField, perPageField);
    this.lastQuery = store.query;
    search && this.search(undefined, undefined, undefined, loadDataOnceFetchOnFilter !== false, isInit);
  };
  CRUD.prototype.handleBulkGo = function (selectedItems, unSelectedItems, e) {
    var _this = this;
    var action = this.props.store.selectedAction;
    var env = this.props.env;
    var confirmText = '';
    if (action.confirmText && (confirmText = amisCore.filter(action.confirmText, this.props.store.mergedData))) {
      return env.confirm(confirmText).then(function (confirmed) {
        return confirmed && _this.handleBulkAction(selectedItems, unSelectedItems, e, action);
      });
    }
    return this.handleBulkAction(selectedItems, unSelectedItems, e, action);
  };
  CRUD.prototype.handleDialogConfirm = function (values, action, ctx, components) {
    var _a;
    var _b, _c, _d;
    var _e = this.props,
      store = _e.store,
      pageField = _e.pageField,
      stopAutoRefreshWhenModalIsOpen = _e.stopAutoRefreshWhenModalIsOpen,
      interval = _e.interval,
      silentPolling = _e.silentPolling,
      env = _e.env;
    store.closeDialog(true, values);
    var dialogAction = store.action;
    if (stopAutoRefreshWhenModalIsOpen && interval) {
      this.timer = setTimeout(silentPolling ? this.silentSearch : this.search, Math.max(interval, 1000));
    }
    if (action.actionType === 'next' && typeof ctx.nextIndex === 'number' && store.data.items[ctx.nextIndex]) {
      return this.handleAction(undefined, tslib.__assign({}, dialogAction), amisCore.createObject(amisCore.createObject(store.data, {
        index: ctx.nextIndex
      }), store.data.items[ctx.nextIndex]));
    } else if (action.actionType === 'prev' && typeof ctx.prevIndex === 'number' && store.data.items[ctx.prevIndex]) {
      return this.handleAction(undefined, tslib.__assign({}, dialogAction), amisCore.createObject(amisCore.createObject(store.data, {
        index: ctx.prevIndex
      }), store.data.items[ctx.prevIndex]));
    } else if (values.length) {
      var value = values[0];
      ctx = amisCore.createObject(ctx, value);
      var component = components[0];
      // 提交来自 form
      if (component && component.props.type === 'form') {
        // 数据保存了，说明列表数据已经无效了，重新刷新。
        if (value && value.__saved) {
          var reload_1 = (_b = action.reload) !== null && _b !== void 0 ? _b : dialogAction.reload;
          // 配置了 reload 则跳过自动更新。
          reload_1 || this.search(dialogAction.__from ? (_a = {}, _a[pageField || 'page'] = 1, _a) : undefined, undefined, true, true);
        } else if (value && (value.hasOwnProperty('items') && value.items || value.hasOwnProperty('ids')) && this.control.bulkUpdate) {
          this.control.bulkUpdate(value, value.items);
        }
      }
    }
    var reload = (_c = action.reload) !== null && _c !== void 0 ? _c : dialogAction.reload;
    if (reload) {
      this.reloadTarget(amisCore.filterTarget(reload, ctx), ctx);
    }
    var redirect = (_d = action.redirect) !== null && _d !== void 0 ? _d : dialogAction.redirect;
    redirect = redirect && amisCore.filter(redirect, ctx);
    redirect && env.jumpTo(redirect, dialogAction, ctx);
  };
  CRUD.prototype.handleDialogClose = function (confirmed) {
    if (confirmed === void 0) {
      confirmed = false;
    }
    var _a = this.props,
      store = _a.store,
      stopAutoRefreshWhenModalIsOpen = _a.stopAutoRefreshWhenModalIsOpen,
      silentPolling = _a.silentPolling,
      interval = _a.interval;
    store.closeDialog(confirmed);
    if (stopAutoRefreshWhenModalIsOpen && interval) {
      this.timer = setTimeout(silentPolling ? this.silentSearch : this.search, Math.max(interval, 1000));
    }
  };
  CRUD.prototype.openFeedback = function (dialog, ctx) {
    var _this = this;
    return new Promise(function (resolve) {
      var store = _this.props.store;
      store.setCurrentAction({
        type: 'button',
        actionType: 'dialog',
        dialog: dialog
      }, _this.props.resolveDefinitions);
      store.openDialog(ctx, undefined, function (confirmed) {
        resolve(confirmed);
      }, _this.context);
    });
  };
  CRUD.prototype.search = function (values, silent, clearSelection, forceReload, isInit) {
    var _a, _b, _c, _d, _e, _f;
    if (forceReload === void 0) {
      forceReload = false;
    }
    if (isInit === void 0) {
      isInit = false;
    }
    return tslib.__awaiter(this, void 0, void 0, function () {
      var _g, store, api, messages, pageField, perPageField, totalField, interval, stopAutoRefreshWhen, stopAutoRefreshWhenModalIsOpen, silentPolling, syncLocation, syncResponse2Query, pickerMode, env, loadDataOnce, loadDataOnceFetchOnFilter, source, columns, dispatchEvent, options, loadDataMode, data, matchFunc, value, page, lastPage, msg, error, rendererEvent, rendererEvent, val;
      var _h;
      return tslib.__generator(this, function (_j) {
        switch (_j.label) {
          case 0:
            _g = this.props, store = _g.store, api = _g.api, messages = _g.messages, pageField = _g.pageField, perPageField = _g.perPageField, totalField = _g.totalField, interval = _g.interval, stopAutoRefreshWhen = _g.stopAutoRefreshWhen, stopAutoRefreshWhenModalIsOpen = _g.stopAutoRefreshWhenModalIsOpen, silentPolling = _g.silentPolling, syncLocation = _g.syncLocation, syncResponse2Query = _g.syncResponse2Query, pickerMode = _g.pickerMode, env = _g.env, loadDataOnce = _g.loadDataOnce, loadDataOnceFetchOnFilter = _g.loadDataOnceFetchOnFilter, source = _g.source, columns = _g.columns, dispatchEvent = _g.dispatchEvent, options = _g.options;
            // reload 需要清空用户选择，无论是否开启keepItemSelectionOnPageChange
            if (clearSelection && !pickerMode) {
              store.resetSelection();
            }
            loadDataMode = '';
            if (values && typeof values.loadDataMode === 'string') {
              loadDataMode = 'load-more';
              delete values.loadDataMode;
            }
            clearTimeout(this.timer);
            values && store.updateQuery(values, !loadDataMode && syncLocation && env && env.updateLocation ? env.updateLocation : undefined, pageField, perPageField);
            this.lastQuery = store.query;
            data = amisCore.createObject(store.data, store.query);
            matchFunc = ((_a = this.props) === null || _a === void 0 ? void 0 : _a.matchFunc) && typeof this.props.matchFunc === 'string' ? amisCore.str2function(this.props.matchFunc, 'items', 'itemsRaw', 'options') : undefined;
            if (!amisCore.isEffectiveApi(api, data)) return [3 /*break*/, 8];
            return [4 /*yield*/, store.fetchInitData(api, data, {
              successMessage: messages && messages.fetchSuccess,
              errorMessage: messages && messages.fetchFailed,
              autoAppend: true,
              forceReload: forceReload,
              loadDataOnce: loadDataOnce,
              source: source,
              silent: silent,
              pageField: pageField,
              perPageField: perPageField,
              totalField: totalField,
              loadDataMode: loadDataMode,
              syncResponse2Query: syncResponse2Query,
              columns: (_b = store.columns) !== null && _b !== void 0 ? _b : columns,
              matchFunc: matchFunc,
              filterOnAllColumns: loadDataOnceFetchOnFilter === false,
              minLoadingTime: values === null || values === void 0 ? void 0 : values.minLoadingTime,
              dataAppendTo: values === null || values === void 0 ? void 0 : values.dataAppendTo
            })];
          case 1:
            value = _j.sent();
            if (!mobxStateTree.isAlive(store)) {
              return [2 /*return*/, value];
            }
            page = store.page, lastPage = store.lastPage, msg = store.msg, error = store.error;
            if (!isInit) return [3 /*break*/, 3];
            return [4 /*yield*/, dispatchEvent === null || dispatchEvent === void 0 ? void 0 : dispatchEvent('fetchInited', amisCore.createObject(this.props.data, {
              responseData: (value === null || value === void 0 ? void 0 : value.ok) ? (_c = store.data) !== null && _c !== void 0 ? _c : {} : value,
              responseStatus: (value === null || value === void 0 ? void 0 : value.status) === undefined ? error ? 1 : 0 : value === null || value === void 0 ? void 0 : value.status,
              responseMsg: msg
            }))];
          case 2:
            rendererEvent = _j.sent();
            if (rendererEvent === null || rendererEvent === void 0 ? void 0 : rendererEvent.prevented) {
              return [2 /*return*/, store.data];
            }
            return [3 /*break*/, 5];
          case 3:
            return [4 /*yield*/, dispatchEvent === null || dispatchEvent === void 0 ? void 0 : dispatchEvent('research', amisCore.createObject(this.props.data, {
              responseData: (value === null || value === void 0 ? void 0 : value.ok) ? (_d = store.data) !== null && _d !== void 0 ? _d : {} : value,
              responseStatus: (value === null || value === void 0 ? void 0 : value.status) === undefined ? error ? 1 : 0 : value === null || value === void 0 ? void 0 : value.status,
              responseMsg: msg
            }))];
          case 4:
            rendererEvent = _j.sent();
            if (rendererEvent === null || rendererEvent === void 0 ? void 0 : rendererEvent.prevented) {
              return [2 /*return*/, store.data];
            }
            _j.label = 5;
          case 5:
            if (!(!loadDataOnce && !store.data.items.length && !interval && page > 1 && lastPage < page)) return [3 /*break*/, 7];
            return [4 /*yield*/, this.search(tslib.__assign(tslib.__assign({}, store.query), (_h = {}, _h[pageField || 'page'] = lastPage, _h)), false, undefined)];
          case 6:
            _j.sent();
            _j.label = 7;
          case 7:
            (value === null || value === void 0 ? void 0 : value.ok) &&
            // 接口正常返回才继续轮训
            interval && this.mounted && (!stopAutoRefreshWhen || !(stopAutoRefreshWhenModalIsOpen && store.hasModalOpened || amisCore.evalExpression(stopAutoRefreshWhen, amisCore.createObject(store.data, store.query)))) && (this.timer = setTimeout(silentPolling ? this.silentSearch.bind(this, undefined, undefined, true) : this.search.bind(this, undefined, undefined, undefined, true), Math.max(interval, 1000)));
            return [3 /*break*/, 9];
          case 8:
            if (source) {
              store.initFromScope(data, source, {
                columns: (_e = store.columns) !== null && _e !== void 0 ? _e : columns,
                matchFunc: matchFunc,
                totalField: totalField
              });
            } else if (pickerMode) {
              store.initFromScope({
                items: options || []
              }, '${items}', {
                columns: (_f = store.columns) !== null && _f !== void 0 ? _f : columns,
                matchFunc: matchFunc,
                totalField: totalField
              });
            }
            _j.label = 9;
          case 9:
            if (this.props.pickerMode && this.props.onSelect && (
            // embed 模式下才同步外部选择，否则是弹窗模式，props.value 不会变化，所以不会记录分页选择，会出现错误
            val = amisCore.getPropValue(this.props))) {
              this.syncSelectedFromPicker(val);
            }
            return [2 /*return*/, store.data];
        }
      });
    });
  };
  CRUD.prototype.silentSearch = function (values, clearSelection, forceReload) {
    if (forceReload === void 0) {
      forceReload = false;
    }
    return this.search(values, true, clearSelection, forceReload);
  };
  CRUD.prototype.handleChangePage = function (page, perPage, dir) {
    var _a;
    return tslib.__awaiter(this, void 0, void 0, function () {
      var _b, store, syncLocation, env, pageField, perPageField, pageDirectionField, autoJumpToTopOnPagerChange, __, api, loadDataOnce, confirmed, query, scrolledY;
      var _c;
      return tslib.__generator(this, function (_d) {
        switch (_d.label) {
          case 0:
            _b = this.props, store = _b.store, syncLocation = _b.syncLocation, env = _b.env, pageField = _b.pageField, perPageField = _b.perPageField, pageDirectionField = _b.pageDirectionField, autoJumpToTopOnPagerChange = _b.autoJumpToTopOnPagerChange, __ = _b.translate, api = _b.api, loadDataOnce = _b.loadDataOnce;
            if (!(api && !loadDataOnce && ((_a = this.control) === null || _a === void 0 ? void 0 : _a.hasModifiedItems()))) return [3 /*break*/, 2];
            return [4 /*yield*/, _confirm__default["default"](__('CRUD.confirmLeaveUnSavedPage'))];
          case 1:
            confirmed = _d.sent();
            if (!confirmed) {
              return [2 /*return*/];
            }
            _d.label = 2;
          case 2:
            query = (_c = {}, _c[pageField || 'page'] = page, _c);
            if (dir) {
              query[pageDirectionField || 'pageDir'] = dir;
            }
            if (perPage) {
              query[perPageField || 'perPage'] = perPage;
            }
            store.updateQuery(query, syncLocation && (env === null || env === void 0 ? void 0 : env.updateLocation) ? env.updateLocation : undefined, pageField, perPageField);
            this.search(undefined, undefined, undefined);
            if (autoJumpToTopOnPagerChange && this.control) {
              if (this.control.scrollToTop) {
                this.control.scrollToTop();
              } else {
                ReactDOM.findDOMNode(this.control).scrollIntoView();
                scrolledY = window.scrollY;
                scrolledY && window.scroll(0, scrolledY);
              }
            }
            return [2 /*return*/];
        }
      });
    });
  };
  CRUD.prototype.syncSelectedFromPicker = function (value) {
    var _a = this.props,
      store = _a.store,
      primaryField = _a.primaryField,
      strictMode = _a.strictMode;
    var isSameValue = function (a, b) {
      var oldValue = a[primaryField || 'id'];
      var itemValue = b[primaryField || 'id'];
      var isSame = strictMode ? oldValue === itemValue : oldValue == itemValue;
      return !!(a === b || oldValue && isSame);
    };
    var selectedItems = value.map(function (item) {
      var _a;
      if (!isPlainObject__default["default"](item)) {
        item = (_a = {}, _a[primaryField || 'id'] = item, _a);
      }
      return amisCore.findTree(store.items, function (a) {
        return isSameValue(a, item);
      }) || item;
    });
    this.props.store.setSelectedItems(selectedItems);
  };
  CRUD.prototype.handleItemChange = function (item, diff, index) {
    var store = this.props.store;
    var indexes = "".concat(index).split('.').map(function (item) {
      return parseInt(item, 10);
    });
    var items = amisCore.spliceTree(store.items, indexes, 1, item);
    store.replaceItems(items);
  };
  CRUD.prototype.handleSave = function (rows, diff, indexes, unModifiedItems, rowsOrigin, options) {
    var _this = this;
    var _a = this.props,
      store = _a.store,
      quickSaveApi = _a.quickSaveApi,
      quickSaveItemApi = _a.quickSaveItemApi,
      primaryField = _a.primaryField,
      env = _a.env,
      messages = _a.messages,
      reload = _a.reload,
      dispatchEvent = _a.dispatchEvent;
    if (Array.isArray(rows)) {
      if (!amisCore.isEffectiveApi(quickSaveApi)) {
        env && env.alert('CRUD quickSaveApi is required');
        return;
      }
      var data_1 = amisCore.createObject(store.data, {
        rows: rows,
        rowsDiff: diff,
        indexes: indexes,
        rowsOrigin: rowsOrigin
      });
      if (rows.length && rows[0].hasOwnProperty(primaryField || 'id')) {
        data_1.ids = rows.map(function (item) {
          return item[primaryField || 'id'];
        }).join(',');
      }
      if (unModifiedItems) {
        data_1.unModifiedItems = unModifiedItems;
      }
      return store.saveRemote(quickSaveApi, data_1, {
        successMessage: messages && messages.saveFailed,
        errorMessage: messages && messages.saveSuccess
      }).then(function (result) {
        return tslib.__awaiter(_this, void 0, void 0, function () {
          var event, finalReload;
          var _a;
          return tslib.__generator(this, function (_b) {
            switch (_b.label) {
              case 0:
                // 如果请求 cancel 了，会来到这里
                if (!result) {
                  return [2 /*return*/];
                }
                return [4 /*yield*/, dispatchEvent === null || dispatchEvent === void 0 ? void 0 : dispatchEvent('quickSaveSucc', amisCore.extendObject(data_1, {
                  result: result
                }))];
              case 1:
                event = _b.sent();
                if (event === null || event === void 0 ? void 0 : event.prevented) {
                  return [2 /*return*/];
                }
                finalReload = (_a = options === null || options === void 0 ? void 0 : options.reload) !== null && _a !== void 0 ? _a : reload;
                return [2 /*return*/, finalReload ? this.reloadTarget(amisCore.filterTarget(finalReload, data_1), data_1) : this.search(undefined, undefined, true, true)];
            }
          });
        });
      }).catch(function (err) {
        return tslib.__awaiter(_this, void 0, void 0, function () {
          return tslib.__generator(this, function (_a) {
            switch (_a.label) {
              case 0:
                return [4 /*yield*/, dispatchEvent === null || dispatchEvent === void 0 ? void 0 : dispatchEvent('quickSaveFail', amisCore.createObject(this.props.data, {
                  error: err
                }))];
              case 1:
                _a.sent();
                return [2 /*return*/];
            }
          });
        });
      });
    } else {
      if (!amisCore.isEffectiveApi(quickSaveItemApi)) {
        env && env.alert('CRUD quickSaveItemApi is required!');
        return;
      }
      var data_2 = amisCore.createObject(store.data, {
        item: rows,
        modified: diff,
        origin: rowsOrigin
      });
      var sendData = amisCore.createObject(data_2, rows);
      return store.saveRemote(quickSaveItemApi, sendData).then(function (result) {
        return tslib.__awaiter(_this, void 0, void 0, function () {
          var event, finalReload;
          var _a;
          return tslib.__generator(this, function (_b) {
            switch (_b.label) {
              case 0:
                // 如果请求 cancel 了，会来到这里
                if (!result) {
                  return [2 /*return*/];
                }
                return [4 /*yield*/, dispatchEvent === null || dispatchEvent === void 0 ? void 0 : dispatchEvent('quickSaveItemSucc', amisCore.extendObject(data_2, {
                  result: result
                }))];
              case 1:
                event = _b.sent();
                if (event === null || event === void 0 ? void 0 : event.prevented) {
                  return [2 /*return*/];
                }
                finalReload = (_a = options === null || options === void 0 ? void 0 : options.reload) !== null && _a !== void 0 ? _a : reload;
                return [2 /*return*/, finalReload ? this.reloadTarget(amisCore.filterTarget(finalReload, data_2), data_2) : this.search(undefined, undefined, true, true)];
            }
          });
        });
      }).catch(function (err) {
        return tslib.__awaiter(_this, void 0, void 0, function () {
          return tslib.__generator(this, function (_a) {
            switch (_a.label) {
              case 0:
                (options === null || options === void 0 ? void 0 : options.resetOnFailed) && this.control.reset();
                return [4 /*yield*/, dispatchEvent === null || dispatchEvent === void 0 ? void 0 : dispatchEvent('quickSaveItemFail', amisCore.createObject(this.props.data, {
                  error: err
                }))];
              case 1:
                _a.sent();
                return [2 /*return*/];
            }
          });
        });
      });
    }
  };
  CRUD.prototype.handleSaveOrder = function (moved, rows) {
    var _this = this;
    var _a = this.props,
      store = _a.store,
      saveOrderApi = _a.saveOrderApi,
      orderField = _a.orderField,
      primaryField = _a.primaryField,
      env = _a.env,
      reload = _a.reload,
      dispatchEvent = _a.dispatchEvent;
    if (!saveOrderApi) {
      env && env.alert('CRUD saveOrderApi is required!');
      return;
    }
    var model = amisCore.createObject(store.data);
    var insertAfter;
    var insertBefore;
    var holding = [];
    var hasIdField = primaryField && rows[0] && rows[0].hasOwnProperty(primaryField);
    hasIdField || (model.idMap = {});
    model.insertAfter = {};
    rows.forEach(function (item) {
      if (~moved.indexOf(item)) {
        if (insertAfter) {
          var insertAfterId = hasIdField ? insertAfter[primaryField] : rows.indexOf(insertAfter);
          model.insertAfter[insertAfterId] = model.insertAfter[insertAfterId] || [];
          hasIdField || (model.idMap[insertAfterId] = insertAfter);
          model.insertAfter[insertAfterId].push(hasIdField ? item[primaryField] : item);
        } else {
          holding.push(item);
        }
      } else {
        insertAfter = item;
        insertBefore = insertBefore || item;
      }
    });
    if (insertBefore && holding.length) {
      var insertBeforeId = hasIdField ? insertBefore[primaryField] : rows.indexOf(insertBefore);
      hasIdField || (model.idMap[insertBeforeId] = insertBefore);
      model.insertBefore = {};
      model.insertBefore[insertBeforeId] = holding.map(function (item) {
        return hasIdField ? item[primaryField] : item;
      });
    } else if (holding.length) {
      var first = holding[0];
      var firstId = hasIdField ? first[primaryField] : rows.indexOf(first);
      hasIdField || (model.idMap[firstId] = first);
      model.insertAfter[firstId] = holding.slice(1).map(function (item) {
        return hasIdField ? item[primaryField] : item;
      });
    }
    if (orderField) {
      var start_1 = (store.page - 1) * store.perPage || 0;
      rows = amisCore.mapTree(rows, function (item, key, level) {
        var _a;
        return amisCore.extendObject(item, (_a = {}, _a[orderField] = (level === 1 ? start_1 : 0) + key + 1, _a));
      });
    }
    model.rows = rows.concat();
    if (hasIdField) {
      var joinIdFields_1 = function (items) {
        return items.map(function (item) {
          return "".concat(item[primaryField]).concat(Array.isArray(item.children) && item.children.length ? "[".concat(joinIdFields_1(item.children), "]") : '');
        }).join(',');
      };
      model.ids = joinIdFields_1(rows);
      orderField && (model.order = amisCore.mapTree(rows, function (item) {
        return pick__default["default"](item, [primaryField, orderField, 'children']);
      }));
    }
    return amisCore.isEffectiveApi(saveOrderApi, model) && store.saveRemote(saveOrderApi, model).then(function (result) {
      return tslib.__awaiter(_this, void 0, void 0, function () {
        var event;
        return tslib.__generator(this, function (_a) {
          switch (_a.label) {
            case 0:
              // 如果请求 cancel 了，会来到这里
              if (!result) {
                return [2 /*return*/];
              }
              return [4 /*yield*/, dispatchEvent === null || dispatchEvent === void 0 ? void 0 : dispatchEvent('saveOrderSucc', amisCore.extendObject(model, {
                result: result
              }))];
            case 1:
              event = _a.sent();
              if (event === null || event === void 0 ? void 0 : event.prevented) {
                return [2 /*return*/];
              }
              reload && this.reloadTarget(amisCore.filterTarget(reload, model), model);
              this.search(undefined, undefined, true, true);
              return [2 /*return*/];
          }
        });
      });
    }).catch(function (err) {
      return tslib.__awaiter(_this, void 0, void 0, function () {
        return tslib.__generator(this, function (_a) {
          switch (_a.label) {
            case 0:
              return [4 /*yield*/, dispatchEvent === null || dispatchEvent === void 0 ? void 0 : dispatchEvent('saveOrderFail', amisCore.createObject(this.props.data, {
                error: err
              }))];
            case 1:
              _a.sent();
              return [2 /*return*/];
          }
        });
      });
    });
  };
  CRUD.prototype.handleSelect = function (items, unSelectedItems) {
    var _a = this.props,
      store = _a.store,
      keepItemSelectionOnPageChange = _a.keepItemSelectionOnPageChange,
      primaryField = _a.primaryField,
      multiple = _a.multiple,
      pickerMode = _a.pickerMode,
      strictMode = _a.strictMode,
      onSelect = _a.onSelect;
    var newItems = items;
    if (keepItemSelectionOnPageChange && store.selectedItems.length) {
      var compareFn_1;
      // 这个是 loadDataOnce 前端分页模式
      if (store.items.length > items.length + unSelectedItems.length) {
        compareFn_1 = function (a, b) {
          return (a.__pristine || a) === (b.__pristine || b);
        };
      } else {
        // 这个是后端分页模式
        compareFn_1 = function (a, b) {
          var oldValue = a[primaryField || 'id'];
          var itemValue = b[primaryField || 'id'];
          var isSame = strictMode ? oldValue === itemValue : oldValue == itemValue;
          return a === b || oldValue && isSame;
        };
      }
      var itemsRest_1 = items.concat();
      newItems = store.selectedItems.map(function (item) {
        var idx = itemsRest_1.findIndex(function (a) {
          return compareFn_1(a, item);
        });
        if (~idx) {
          return itemsRest_1.splice(idx, 1)[0];
        }
        return amisCore.findTree(unSelectedItems, function (a) {
          return compareFn_1(a, item);
        }) ? null : item;
      }).filter(function (item) {
        return item;
      }).concat(itemsRest_1);
    }
    var newUnSelectedItems = store.items.filter(function (item) {
      return !newItems.find(function (a) {
        return (a.__pristine || a) === item;
      });
    }).map(function (item) {
      return unSelectedItems.find(function (a) {
        return a.__pristine === item;
      }) || item;
    });
    // if (keepItemSelectionOnPageChange && store.selectedItems.length) {
    //   const oldItems = store.selectedItems.concat();
    //   const oldUnselectedItems = store.unSelectedItems.concat();
    //   const isSameValue = (
    //     a: Record<string, unknown>,
    //     item: Record<string, unknown>
    //   ) => {
    //     const oldValue = a[primaryField || 'id'];
    //     const itemValue = item[primaryField || 'id'];
    //     const isSame = strictMode
    //       ? oldValue === itemValue
    //       : oldValue == itemValue;
    //     return a === item || (oldValue && isSame);
    //   };
    //   items.forEach(item => {
    //     const idx = findIndex(oldItems, a => isSameValue(a, item));
    //     if (~idx) {
    //       oldItems[idx] = item;
    //     } else {
    //       oldItems.push(item);
    //     }
    //     const idx2 = findIndex(oldUnselectedItems, a => isSameValue(a, item));
    //     if (~idx2) {
    //       oldUnselectedItems.splice(idx2, 1);
    //     }
    //   });
    //   unSelectedItems.forEach(item => {
    //     const idx = findIndex(oldUnselectedItems, a => isSameValue(a, item));
    //     const idx2 = findIndex(oldItems, a => isSameValue(a, item));
    //     if (~idx) {
    //       oldUnselectedItems[idx] = item;
    //     } else {
    //       oldUnselectedItems.push(item);
    //     }
    //     !~idx && ~idx2 && oldItems.splice(idx2, 1);
    //   });
    //   newItems = oldItems;
    //   newUnSelectedItems = oldUnselectedItems;
    //   // const thisBatch = items.concat(unSelectedItems);
    //   // let notInThisBatch = (item: any) =>
    //   //   !find(
    //   //     thisBatch,
    //   //     a => a[primaryField || 'id'] == item[primaryField || 'id']
    //   //   );
    //   // newItems = store.selectedItems.filter(notInThisBatch);
    //   // newUnSelectedItems = store.unSelectedItems.filter(notInThisBatch);
    //   // newItems.push(...items);
    //   // newUnSelectedItems.push(...unSelectedItems);
    // }
    if (pickerMode && multiple === false && newItems.length > 1) {
      newUnSelectedItems.push.apply(newUnSelectedItems, newItems.splice(0, newItems.length - 1));
    }
    // 用 updateSelectData 导致 CRUD 无限刷新
    // store.updateSelectData(newItems, newUnSelectedItems);
    store.setSelectedItems(newItems);
    store.setUnSelectedItems(newUnSelectedItems);
    onSelect && onSelect(newItems, newUnSelectedItems);
  };
  CRUD.prototype.handleChildPopOverOpen = function (popOver) {
    if (this.props.interval && popOver && ~['dialog', 'drawer'].indexOf(popOver.mode)) {
      this.props.stopAutoRefreshWhenModalIsOpen && clearTimeout(this.timer);
      this.props.store.setInnerModalOpened(true);
    }
  };
  CRUD.prototype.handleChildPopOverClose = function (popOver) {
    var _a = this.props,
      stopAutoRefreshWhenModalIsOpen = _a.stopAutoRefreshWhenModalIsOpen,
      silentPolling = _a.silentPolling,
      interval = _a.interval;
    if (popOver && ~['dialog', 'drawer'].indexOf(popOver.mode)) {
      this.props.store.setInnerModalOpened(false);
      if (stopAutoRefreshWhenModalIsOpen && interval) {
        this.timer = setTimeout(silentPolling ? this.silentSearch : this.search, Math.max(interval, 1000));
      }
    }
  };
  CRUD.prototype.handleQuery = function (values, forceReload, replace, resetPage, clearSelection) {
    var _a;
    var _b = this.props,
      store = _b.store,
      syncLocation = _b.syncLocation,
      env = _b.env,
      pageField = _b.pageField,
      perPageField = _b.perPageField,
      loadDataOnceFetchOnFilter = _b.loadDataOnceFetchOnFilter;
    store.updateQuery(resetPage ? tslib.__assign((_a = {}, _a[pageField || 'page'] = 1, _a), values) : values, syncLocation && env && env.updateLocation ? env.updateLocation : undefined, pageField, perPageField, replace);
    return this.search(undefined, undefined, clearSelection !== null && clearSelection !== void 0 ? clearSelection : replace, forceReload !== null && forceReload !== void 0 ? forceReload : loadDataOnceFetchOnFilter === true);
  };
  CRUD.prototype.reload = function (subpath, query, ctx, silent, replace, args) {
    if (query) {
      return this.receive(query, undefined, replace, args === null || args === void 0 ? void 0 : args.resetPage, true);
    } else {
      return this.search(undefined, undefined, true, true);
    }
  };
  CRUD.prototype.receive = function (values, subPath, replace, resetPage, clearSelection) {
    return this.handleQuery(values, true, replace, resetPage, clearSelection);
  };
  CRUD.prototype.reloadTarget = function (target, data) {
    // implement this.
  };
  CRUD.prototype.closeTarget = function (target) {
    // implement this.
  };
  CRUD.prototype.doAction = function (action, data, throwErrors, args) {
    var _a;
    if (throwErrors === void 0) {
      throwErrors = false;
    }
    return tslib.__awaiter(this, void 0, void 0, function () {
      var store, selectedItems_1, unSelectedItems;
      return tslib.__generator(this, function (_b) {
        switch (_b.label) {
          case 0:
            store = this.props.store;
            if (!(action.actionType && ['submitQuickEdit', 'toggleExpanded', 'setExpanded', 'initDrag', 'cancelDrag', 'selectAll', 'clearAll'].includes(action.actionType))) return [3 /*break*/, 1];
            return [2 /*return*/, (_a = this.control) === null || _a === void 0 ? void 0 : _a.doAction(action, data, throwErrors, args)];
          case 1:
            if (!(action.actionType === 'select')) return [3 /*break*/, 3];
            return [4 /*yield*/, amisCore.getMatchedEventTargets(store.items, data, args === null || args === void 0 ? void 0 : args.index, args === null || args === void 0 ? void 0 : args.condition)];
          case 2:
            selectedItems_1 = _b.sent();
            unSelectedItems = store.items.filter(function (item) {
              return !selectedItems_1.includes(item);
            });
            // todo 这里的 selected 和 unselected 不是修改后的
            //
            return [2 /*return*/, this.handleSelect(selectedItems_1, unSelectedItems)];
          case 3:
            return [2 /*return*/, this.handleAction(undefined, action, data, throwErrors)];
        }
      });
    });
  };
  CRUD.prototype.dispatchEvent = function (e, data, renderer,
  // for didmount
  scoped) {
    // 如果事件是 selectedChange 并且是当前组件触发的，
    // 则以当前组件的选择信息为准
    if (e === 'selectedChange' && this.control === renderer) {
      var store = this.props.store;
      data.selectedItems = store.selectedItems.concat();
      data.unSelectedItems = store.unSelectedItems.concat();
      // selectedIndexes  还不支持
    }
    return this.props.dispatchEvent(e, data, renderer, scoped);
  };
  CRUD.prototype.unSelectItem = function (item, index) {
    var store = this.props.store;
    var selected = store.selectedItems.concat();
    var unSelected = store.unSelectedItems.concat();
    var idx = selected.indexOf(item);
    ~idx && unSelected.push.apply(unSelected, selected.splice(idx, 1));
    store.setSelectedItems(selected);
    store.setUnSelectedItems(unSelected);
  };
  CRUD.prototype.clearSelection = function () {
    var _a = this.props,
      store = _a.store,
      itemCheckableOn = _a.itemCheckableOn;
    var _b = tslib.__read(partition__default["default"](store.selectedItems, function (item) {
        return !itemCheckableOn || amisCore.evalExpression(itemCheckableOn, item);
      }), 2),
      unchecked = _b[0],
      checked = _b[1];
    var unSelected = store.unSelectedItems.concat(unchecked);
    store.setSelectedItems(checked);
    store.setUnSelectedItems(unSelected);
  };
  CRUD.prototype.hasBulkActionsToolbar = function () {
    var _a = this.props,
      headerToolbar = _a.headerToolbar,
      footerToolbar = _a.footerToolbar,
      enableBulkActions = _a.enableBulkActions;
    if (enableBulkActions === false) {
      return false;
    }
    var isBulkActions = function (item) {
      return ~['bulkActions', 'bulk-actions'].indexOf(item.type || item);
    };
    return Array.isArray(headerToolbar) && find__default["default"](headerToolbar, isBulkActions) || Array.isArray(footerToolbar) && find__default["default"](footerToolbar, isBulkActions);
  };
  CRUD.prototype.hasBulkActions = function () {
    var _a = this.props,
      bulkActions = _a.bulkActions,
      itemActions = _a.itemActions,
      store = _a.store;
    if (!bulkActions || !bulkActions.length) {
      return false;
    }
    var bulkBtns = [];
    var ctx = store.mergedData;
    if (bulkActions && bulkActions.length) {
      bulkBtns = bulkActions.map(function (item) {
        return tslib.__assign(tslib.__assign({}, item), amisCore.getExprProperties(item, ctx));
      }).filter(function (item) {
        return !item.hidden && item.visible !== false;
      });
    }
    return bulkBtns.length;
  };
  CRUD.prototype.renderBulkActions = function (childProps) {
    var _this = this;
    var _a;
    var _b = this.props,
      bulkActions = _b.bulkActions,
      itemActions = _b.itemActions,
      store = _b.store,
      render = _b.render,
      cx = _b.classnames,
      primaryField = _b.primaryField,
      enableBulkActions = _b.enableBulkActions;
    if (!bulkActions || !bulkActions.length || enableBulkActions === false) {
      return null;
    }
    var selectedItems = store.selectedItems;
    var unSelectedItems = store.unSelectedItems;
    var bulkBtns = [];
    var itemBtns = [];
    var ctx = amisCore.createObject(store.mergedData, tslib.__assign(tslib.__assign({
      currentPageData: (((_a = store.mergedData) === null || _a === void 0 ? void 0 : _a.items) || []).concat()
    }, store.eventContext), {
      rows: selectedItems.concat(),
      items: selectedItems.concat(),
      ids: selectedItems.map(function (item) {
        return item.hasOwnProperty(primaryField) ? item[primaryField] : null;
      }).filter(function (item) {
        return item;
      }).join(',')
    }));
    // const ctx = createObject(store.data, {
    //     ...store.query,
    //     items: childProps.items,
    //     selectedItems: childProps.selectedItems,
    //     unSelectedItems: childProps.unSelectedItems
    // });
    if (bulkActions && bulkActions.length && (!itemActions || !itemActions.length || selectedItems.length > 1)) {
      bulkBtns = bulkActions.map(function (item) {
        return tslib.__assign(tslib.__assign({}, item), amisCore.getExprProperties(item, ctx));
      }).filter(function (item) {
        return !item.hidden && item.visible !== false;
      });
    }
    var itemData = amisCore.createObject(store.data, selectedItems.length ? selectedItems[0] : {});
    if (itemActions && selectedItems.length <= 1) {
      itemBtns = itemActions.map(function (item) {
        return tslib.__assign(tslib.__assign({}, item), amisCore.getExprProperties(item, itemData));
      }).filter(function (item) {
        return !item.hidden && item.visible !== false;
      });
    }
    return bulkBtns.length || itemBtns.length ? _J$X_("div", {
      className: cx('Crud-actions')
    }, bulkBtns.map(function (btn, index) {
      return render("bulk-action/".concat(index), tslib.__assign(tslib.__assign({}, omit__default["default"](btn, ['visibleOn', 'hiddenOn', 'disabledOn'])), {
        type: btn.type || 'button'
      }), {
        key: "bulk-".concat(index),
        data: ctx,
        disabled: btn.disabled || (btn.requireSelected !== false ? !selectedItems.length : false),
        onAction: _this.handleBulkAction.bind(_this, selectedItems.concat(), unSelectedItems.concat()),
        ignoreConfirm: true
      });
    }), itemBtns.map(function (btn, index) {
      return render("bulk-action/".concat(index), tslib.__assign(tslib.__assign({}, omit__default["default"](btn, ['visibleOn', 'hiddenOn', 'disabledOn'])), {
        type: 'button'
      }), {
        key: "item-".concat(index),
        data: itemData,
        disabled: btn.disabled || selectedItems.length !== 1,
        onAction: _this.handleItemAction.bind(_this, btn, itemData)
      });
    })) : null;
  };
  CRUD.prototype.renderPagination = function (toolbar) {
    var _a = this.props,
      store = _a.store,
      render = _a.render,
      cx = _a.classnames,
      alwaysShowPagination = _a.alwaysShowPagination,
      perPageAvailable = _a.perPageAvailable,
      testIdBuilder = _a.testIdBuilder;
    var page = store.page,
      lastPage = store.lastPage;
    if (store.mode !== 'simple' && store.lastPage < 2 && !alwaysShowPagination) {
      return null;
    }
    var extraProps = {};
    // 下发 perPageAvailable
    if (Array.isArray(perPageAvailable)) {
      extraProps.perPageAvailable = perPageAvailable;
    }
    /** 优先级：showPageInput显性配置 > (lastPage > 9) */
    if (typeof toolbar !== 'string') {
      Object.assign(extraProps, toolbar);
      var showPageInput = toolbar.showPageInput;
      extraProps.showPageInput = showPageInput === true || lastPage > 9 && showPageInput == null;
      extraProps.total = amisCore.resolveVariableAndFilter(toolbar.total, store.data);
    } else {
      extraProps.showPageInput = lastPage > 9;
    }
    return _J$X_("div", {
      className: cx('Crud-pager')
    }, render('pagination', {
      type: 'pagination',
      testIdBuilder: testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('pagination')
    }, tslib.__assign(tslib.__assign({}, extraProps), {
      activePage: page,
      lastPage: lastPage,
      hasNext: store.hasNext,
      mode: store.mode,
      perPage: store.perPage,
      popOverContainer: this.parentContainer,
      onPageChange: this.handleChangePage
    })));
  };
  CRUD.prototype.renderStatistics = function () {
    var _a = this.props,
      store = _a.store,
      cx = _a.classnames,
      __ = _a.translate,
      alwaysShowPagination = _a.alwaysShowPagination;
    if (store.lastPage <= 1 && !alwaysShowPagination) {
      return null;
    }
    return _J$X_("div", {
      className: cx('Crud-statistics')
    }, __('CRUD.stat', {
      page: store.page,
      lastPage: store.lastPage,
      total: store.total
    }));
  };
  CRUD.prototype.renderSwitchPerPage = function (childProps) {
    var _this = this;
    var _a = this.props,
      mobileUI = _a.mobileUI,
      store = _a.store,
      perPageAvailable = _a.perPageAvailable,
      cx = _a.classnames,
      ns = _a.classPrefix,
      __ = _a.translate,
      testIdBuilder = _a.testIdBuilder;
    var items = childProps.items;
    if (!items.length) {
      return null;
    }
    var perPages = mobileUI ? (perPageAvailable || [5, 10, 20, 50, 100]).map(function (item) {
      return {
        label: item + ' 条/页',
        value: item + ''
      };
    }) : (perPageAvailable || [5, 10, 20, 50, 100]).map(function (item) {
      return {
        label: item,
        value: item + ''
      };
    });
    return _J$X_("div", {
      className: cx('Crud-pageSwitch')
    }, !mobileUI ? _J$X_("span", null, __('CRUD.perPage')) : null, _J$X_(_Select__default["default"], {
      classPrefix: ns,
      searchable: false,
      placeholder: __('Select.placeholder'),
      options: perPages,
      value: store.perPage + '',
      onChange: function (value) {
        return _this.handleChangePage(1, value.value);
      },
      clearable: false,
      popOverContainer: this.parentContainer,
      testIdBuilder: testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('perPage')
    }));
  };
  CRUD.prototype.renderLoadMore = function () {
    var _this = this;
    var _a = this.props,
      store = _a.store,
      ns = _a.classPrefix,
      cx = _a.classnames,
      __ = _a.translate,
      testIdBuilder = _a.testIdBuilder,
      _b = _a.loadMoreProps,
      loadMoreProps = _b === void 0 ? {} : _b;
    var page = store.page,
      lastPage = store.lastPage;
    var _c = loadMoreProps.showIcon,
      showIcon = _c === void 0 ? true : _c,
      _d = loadMoreProps.showText,
      showText = _d === void 0 ? true : _d,
      _e = loadMoreProps.iconType,
      iconType = _e === void 0 ? 'loading-outline' : _e,
      _f = loadMoreProps.contentText,
      contentText = _f === void 0 ? {
        contentdown: '点击加载更多',
        contentrefresh: '加载中...',
        contentnomore: '没有更多数据了'
      } : _f,
      minLoadingTime = loadMoreProps.minLoadingTime,
      dataAppendTo = loadMoreProps.dataAppendTo,
      color = loadMoreProps.color;
    var isLoading = store.loading;
    var isNoMore = page >= lastPage;
    return _J$X_("div", {
      className: cx('Crud-loadMore'),
      style: color ? {
        '--Spinner-color': color,
        'color': color
      } : undefined,
      onClick: function () {
        if (isLoading || isNoMore) {
          return;
        }
        _this.search({
          page: page + 1,
          loadDataMode: 'load-more',
          minLoadingTime: minLoadingTime,
          dataAppendTo: dataAppendTo
        });
      }
    }, showIcon && _J$X_(_Spinner__default["default"], {
      show: isLoading,
      icon: iconType,
      size: "sm"
    }), showText && _J$X_("span", null, isLoading ? contentText.contentrefresh : isNoMore ? contentText.contentnomore : contentText.contentdown));
  };
  CRUD.prototype.renderFilterToggler = function () {
    var _a, _b, _c;
    var _d = this.props,
      store = _d.store,
      cx = _d.classnames,
      __ = _d.translate,
      filterTogglable = _d.filterTogglable;
    if (!store.filterTogglable) {
      return null;
    }
    var custom = isPlainObject__default["default"](filterTogglable) ? tslib.__assign({}, filterTogglable) : {};
    if (store.filterVisible) {
      custom.icon = (_a = custom.activeIcon) !== null && _a !== void 0 ? _a : custom.icon;
      custom.label = (_b = custom.activeLabel) !== null && _b !== void 0 ? _b : custom.label;
    }
    return _J$X_("button", {
      onClick: function () {
        return store.setFilterVisible(!store.filterVisible);
      },
      className: cx('Button Button--size-default Button--default', {
        'is-active': store.filterVisible
      })
    }, custom.icon ? _J$X_(_Icon__default["default"], {
      icon: custom.icon,
      className: "icon m-r-xs"
    }) : (custom === null || custom === void 0 ? void 0 : custom.icon) !== false ? _J$X_(_Icon__default["default"], {
      icon: "filter",
      className: "icon m-r-xs"
    }) : null, (_c = custom === null || custom === void 0 ? void 0 : custom.label) !== null && _c !== void 0 ? _c : __('CRUD.filter'));
  };
  CRUD.prototype.renderExportCSV = function (toolbar) {
    var _a = this.props,
      store = _a.store,
      ns = _a.classPrefix,
      __ = _a.translate,
      loadDataOnce = _a.loadDataOnce;
    var api = toolbar.api;
    var filename = toolbar.filename;
    return _J$X_(_Button__default["default"], {
      classPrefix: ns,
      onClick: function () {
        return store.exportAsCSV({
          loadDataOnce: loadDataOnce,
          api: api,
          filename: filename,
          data: store.filterData /* 因为filter区域可能设置了过滤字段值，所以query信息也要写入数据域 */
        });
      }
    }, toolbar.label || __('CRUD.exportCSV'));
  };
  CRUD.prototype.renderToolbar = function (toolbar, index, childProps, toolbarRenderer) {
    var _this = this;
    if (index === void 0) {
      index = 0;
    }
    if (childProps === void 0) {
      childProps = {};
    }
    if (!toolbar) {
      return null;
    }
    var _a = this.props,
      render = _a.render,
      store = _a.store,
      mobileUI = _a.mobileUI,
      __ = _a.translate,
      testIdBuilder = _a.testIdBuilder;
    var type = toolbar.type || toolbar;
    if (type === 'bulkActions' || type === 'bulk-actions') {
      return this.renderBulkActions(childProps);
    } else if (type === 'pagination') {
      return this.renderPagination(toolbar);
    } else if (type === 'statistics') {
      return this.renderStatistics();
    } else if (type === 'switch-per-page') {
      return this.renderSwitchPerPage(childProps);
    } else if (type === 'load-more') {
      return this.renderLoadMore();
    } else if (type === 'filter-toggler') {
      return this.renderFilterToggler();
    } else if (type === 'export-csv') {
      return this.renderExportCSV(toolbar);
    } else if (type === 'reload') {
      var reloadButton = {
        label: '',
        icon: 'fa fa-sync',
        tooltip: __('reload'),
        tooltipPlacement: 'top',
        type: 'button'
      };
      if (typeof toolbar === 'object') {
        reloadButton = tslib.__assign(tslib.__assign({}, reloadButton), omit__default["default"](toolbar, ['type', 'align']));
      }
      return render("toolbar/".concat(index), reloadButton, {
        onAction: function () {
          _this.reload();
        }
      });
    } else if (Array.isArray(toolbar)) {
      var children = toolbar.filter(function (toolbar) {
        return amisCore.isVisible(toolbar, store.toolbarData);
      }).map(function (toolbar, index) {
        return {
          dom: _this.renderToolbar(toolbar, index, childProps, toolbarRenderer),
          toolbar: toolbar
        };
      }).filter(function (item) {
        return item.dom;
      });
      var len = children.length;
      var cx_1 = this.props.classnames;
      if (len) {
        return _J$X_("div", tslib.__assign({
          className: cx_1('Crud-toolbar'),
          key: index
        }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('toolbar').getTestId()), children.map(function (_a, index) {
          var toolbar = _a.toolbar,
            child = _a.dom;
          var type = toolbar.type || toolbar;
          var align = toolbar.align || (type === 'pagination' ? 'right' : 'left');
          return _J$X_("div", {
            key: toolbar.id || index,
            className: cx_1('Crud-toolbar-item', align ? "Crud-toolbar-item--".concat(align) : '', {
              'is-mobile': mobileUI
            }
            // toolbar.className
            )
          }, child);
        }));
      }
      return null;
    }
    var result = toolbarRenderer ? toolbarRenderer(toolbar, index) : undefined;
    if (result !== void 0) {
      return result;
    }
    var $$editable = childProps.$$editable;
    return render("toolbar/".concat(index), toolbar, {
      data: store.toolbarData,
      page: store.page,
      lastPage: store.lastPage,
      perPage: store.perPage,
      total: store.total,
      onQuery: this.handleQuery,
      onAction: this.handleAction,
      onChangePage: this.handleChangePage,
      onBulkAction: this.handleBulkAction,
      $$editable: $$editable
    });
  };
  CRUD.prototype.renderHeaderToolbar = function (childProps, toolbarRenderer) {
    var _a = this.props,
      toolbar = _a.toolbar,
      toolbarInline = _a.toolbarInline,
      headerToolbar = _a.headerToolbar;
    if (toolbar) {
      if (Array.isArray(headerToolbar)) {
        headerToolbar = toolbarInline ? headerToolbar.concat(toolbar) : [headerToolbar, toolbar];
      } else if (headerToolbar) {
        headerToolbar = [headerToolbar, toolbar];
      } else {
        headerToolbar = toolbar;
      }
    }
    return this.renderToolbar(headerToolbar || [], 0, childProps, toolbarRenderer);
  };
  CRUD.prototype.renderFooterToolbar = function (childProps, toolbarRenderer) {
    var _a = this.props,
      toolbar = _a.toolbar,
      toolbarInline = _a.toolbarInline,
      footerToolbar = _a.footerToolbar;
    if (toolbar) {
      if (Array.isArray(footerToolbar)) {
        footerToolbar = toolbarInline ? footerToolbar.concat(toolbar) : [footerToolbar, toolbar];
      } else if (footerToolbar) {
        footerToolbar = [footerToolbar, toolbar];
      } else {
        footerToolbar = toolbar;
      }
    }
    return this.renderToolbar(footerToolbar, 0, childProps, toolbarRenderer);
  };
  CRUD.prototype.renderTag = function (item, index) {
    var _a = this.props,
      cx = _a.classnames,
      labelField = _a.labelField,
      labelTpl = _a.labelTpl,
      primaryField = _a.primaryField,
      valueField = _a.valueField,
      __ = _a.translate,
      env = _a.env,
      itemCheckableOn = _a.itemCheckableOn;
    var checkable = itemCheckableOn ? amisCore.evalExpression(itemCheckableOn, item) : true;
    return _J$X_("div", {
      key: index,
      className: cx("Crud-value", checkable ? '' : 'is-disabled')
    }, _J$X_("span", {
      className: cx('Crud-valueIcon'),
      onClick: this.unSelectItem.bind(this, item, index)
    }, "\u00D7"), _J$X_("span", {
      className: cx('Crud-valueLabel')
    }, labelTpl ? _J$X_(_Html__default["default"], {
      html: amisCore.filter(labelTpl, item),
      filterHtml: env.filterHtml
    }) : amisCore.getVariable(item, labelField || 'label') || amisCore.getVariable(item, valueField || primaryField || 'id')));
  };
  CRUD.prototype.renderSelection = function () {
    var _this = this;
    var _a = this.props,
      store = _a.store,
      ns = _a.classPrefix,
      cx = _a.classnames,
      labelField = _a.labelField,
      labelTpl = _a.labelTpl,
      primaryField = _a.primaryField,
      valueField = _a.valueField,
      __ = _a.translate,
      env = _a.env,
      popOverContainer = _a.popOverContainer,
      multiple = _a.multiple,
      maxTagCount = _a.maxTagCount,
      overflowTagPopover = _a.overflowTagPopover,
      keepItemSelectionOnPageChange = _a.keepItemSelectionOnPageChange;
    if (!store.selectedItems.length || !keepItemSelectionOnPageChange || multiple === false) {
      return null;
    }
    var tags = store.selectedItems;
    var enableOverflow = multiple !== false && typeof maxTagCount === 'number' && maxTagCount > 0;
    var tooltipProps = tslib.__assign({
      offset: [0, -10],
      tooltipClassName: cx('Crud-selection-overflow', overflowTagPopover === null || overflowTagPopover === void 0 ? void 0 : overflowTagPopover.tooltipClassName),
      title: __('已选项')
    }, omit__default["default"](overflowTagPopover, ['children', 'content', 'tooltipClassName']));
    return _J$X_("div", {
      className: cx('Crud-selection')
    }, _J$X_("div", {
      "data-folder-ignore": true,
      className: cx('Crud-selectionLabel')
    }, __('CRUD.selected', {
      total: store.selectedItems.length
    })), _J$X_(_AutoFoldedList__default["default"], {
      enabled: !!enableOverflow,
      tooltipClassName: cx('Crud-selection-overflow-wrapper'),
      items: tags,
      popOverContainer: popOverContainer,
      tooltipOptions: tooltipProps,
      maxVisibleCount: maxTagCount,
      renderItem: function (item, index, folded) {
        return _this.renderTag(item, index);
      }
    }), _J$X_("a", {
      onClick: this.clearSelection,
      className: cx('Crud-selectionClear')
    }, __('clear')));
  };
  CRUD.prototype.renderFilter = function () {
    var _a;
    var _b = this.props,
      store = _b.store,
      render = _b.render,
      cx = _b.classnames,
      filter = _b.filter,
      __ = _b.translate,
      testIdBuilder = _b.testIdBuilder,
      _c = _b.filterCanAccessSuperData,
      filterCanAccessSuperData = _c === void 0 ? true : _c;
    if (!filter || store.filterTogglable && !store.filterVisible) {
      return null;
    }
    return render('filter', tslib.__assign(tslib.__assign({
      title: __('CRUD.filter'),
      mode: 'inline',
      submitText: __('search')
    }, filter), {
      type: 'form',
      api: null,
      testIdBuilder: testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('filter')
    }), {
      key: 'filter',
      panelClassName: cx('Crud-filter', filter.panelClassName || 'Panel--default'),
      data: store.filterData,
      onReset: this.handleFilterReset,
      onSubmit: this.handleFilterSubmit,
      onInit: this.handleFilterInit,
      formStore: undefined,
      canAccessSuperData: (_a = filter === null || filter === void 0 ? void 0 : filter.canAccessSuperData) !== null && _a !== void 0 ? _a : filterCanAccessSuperData
    });
  };
  CRUD.prototype.filterItemIndex = function (index) {
    var _a;
    var store = this.props.store;
    var indexes = "".concat(index).split('.').map(function (index) {
      return parseInt(index, 10);
    });
    if (!Array.isArray(store.data.items)) {
      // something wrong.
      return index;
    }
    var top = (_a = store.data.items) === null || _a === void 0 ? void 0 : _a[indexes[0]];
    if (top) {
      indexes[0] = store.items.findIndex(function (a) {
        return (a.__pristine || a) === (top.__pristine || top);
      });
    }
    return indexes.join('.');
  };
  CRUD.prototype.filterBodySchema = function (subSchema) {
    return subSchema;
  };
  CRUD.prototype.renderBody = function () {
    var _a;
    var _b = this.props,
      className = _b.className,
      style = _b.style,
      bodyClassName = _b.bodyClassName,
      filter = _b.filter,
      render = _b.render,
      store = _b.store,
      mode = _b.mode,
      syncLocation = _b.syncLocation,
      children = _b.children,
      bulkActions = _b.bulkActions,
      pickerMode = _b.pickerMode,
      multiple = _b.multiple,
      strictMode = _b.strictMode,
      valueField = _b.valueField,
      primaryField = _b.primaryField,
      value = _b.value,
      hideQuickSaveBtn = _b.hideQuickSaveBtn,
      itemActions = _b.itemActions,
      cx = _b.classnames,
      keepItemSelectionOnPageChange = _b.keepItemSelectionOnPageChange,
      maxKeepItemSelectionLength = _b.maxKeepItemSelectionLength,
      maxItemSelectionLength = _b.maxItemSelectionLength,
      onAction = _b.onAction,
      popOverContainer = _b.popOverContainer,
      __ = _b.translate,
      onQuery = _b.onQuery,
      autoGenerateFilter = _b.autoGenerateFilter,
      onSelect = _b.onSelect,
      autoFillHeight = _b.autoFillHeight,
      onEvent = _b.onEvent,
      onSave = _b.onSave,
      onSaveOrder = _b.onSaveOrder,
      onPopOverOpened = _b.onPopOverOpened,
      onPopOverClosed = _b.onPopOverClosed,
      onSearchableFromReset = _b.onSearchableFromReset,
      onSearchableFromSubmit = _b.onSearchableFromSubmit,
      onSearchableFromInit = _b.onSearchableFromInit,
      headerToolbarRender = _b.headerToolbarRender,
      footerToolbarRender = _b.footerToolbarRender,
      testIdBuilder = _b.testIdBuilder,
      id = _b.id,
      _c = _b.filterCanAccessSuperData,
      filterCanAccessSuperData = _c === void 0 ? true : _c,
      _d = _b.selectable,
      selectable = _d === void 0 ? false : _d,
      rest = tslib.__rest(_b, ["className", "style", "bodyClassName", "filter", "render", "store", "mode", "syncLocation", "children", "bulkActions", "pickerMode", "multiple", "strictMode", "valueField", "primaryField", "value", "hideQuickSaveBtn", "itemActions", "classnames", "keepItemSelectionOnPageChange", "maxKeepItemSelectionLength", "maxItemSelectionLength", "onAction", "popOverContainer", "translate", "onQuery", "autoGenerateFilter", "onSelect", "autoFillHeight", "onEvent", "onSave", "onSaveOrder", "onPopOverOpened", "onPopOverClosed", "onSearchableFromReset", "onSearchableFromSubmit", "onSearchableFromInit", "headerToolbarRender", "footerToolbarRender", "testIdBuilder", "id", "filterCanAccessSuperData", "selectable"]);
    return render('body', tslib.__assign(tslib.__assign({}, this.filterBodySchema(rest)), {
      id: id,
      // 通用事件 例如cus-event 如果直接透传给table 则会被触发2次
      // 因此只将下层组件table、cards中自定义事件透传下去 否则通过crud配置了也不会执行
      onEvent: this.filterOnEvent(onEvent),
      columns: (_a = store.columns) !== null && _a !== void 0 ? _a : rest.columns,
      type: mode || 'table'
    }), {
      key: 'body',
      className: cx('Crud-body', bodyClassName),
      ref: this.controlRef,
      autoGenerateFilter: !filter && autoGenerateFilter,
      filterCanAccessSuperData: filterCanAccessSuperData,
      autoFillHeight: autoFillHeight,
      selectable: !!(this.hasBulkActionsToolbar() && this.hasBulkActions() || pickerMode || selectable),
      itemActions: itemActions,
      multiple: multiple === void 0 ? bulkActions && bulkActions.length > 0 ? true : false : multiple,
      selected: store.selectedItemsAsArray,
      strictMode: strictMode,
      keepItemSelectionOnPageChange: keepItemSelectionOnPageChange,
      maxKeepItemSelectionLength: maxKeepItemSelectionLength,
      maxItemSelectionLength: maxItemSelectionLength,
      valueField: valueField || primaryField,
      primaryField: primaryField,
      hideQuickSaveBtn: hideQuickSaveBtn,
      items: store.data.items,
      fullItems: store.itemsAsArray,
      query: store.query,
      orderBy: store.query.orderBy,
      orderDir: store.query.orderDir,
      popOverContainer: popOverContainer,
      onAction: this.handleAction,
      dispatchEvent: this.dispatchEvent,
      onItemChange: this.handleItemChange,
      onSave: this.handleSave,
      onSaveOrder: this.handleSaveOrder,
      onQuery: this.handleQuery,
      onSelect: this.handleSelect,
      onPopOverOpened: this.handleChildPopOverOpen,
      onPopOverClosed: this.handleChildPopOverClose,
      onSearchableFromReset: this.handleFilterReset,
      onSearchableFromSubmit: this.handleFilterSubmit,
      onSearchableFromInit: this.handleFilterInit,
      headerToolbarRender: this.renderHeaderToolbar,
      footerToolbarRender: this.renderFooterToolbar,
      data: store.mergedData,
      loading: store.loading,
      offset: store.offset,
      host: this,
      filterItemIndex: this.filterItemIndex,
      onDbClick: this.props.rowDbClick,
      testIdBuilder: testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('body')
    });
  };
  CRUD.prototype.render = function () {
    var _a = this.props,
      className = _a.className,
      style = _a.style,
      render = _a.render,
      store = _a.store,
      cx = _a.classnames,
      __ = _a.translate,
      testIdBuilder = _a.testIdBuilder,
      id = _a.id,
      mobileUI = _a.mobileUI;
    return _J$X_("div", tslib.__assign({
      className: cx('Crud', className, {
        'is-loading': store.loading,
        'is-mobile': mobileUI
      }),
      style: style,
      "data-id": id,
      "data-role": "container"
    }, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('wrapper').getTestId()), this.renderFilter(), this.renderSelection(), this.renderBody(), render('dialog', tslib.__assign(tslib.__assign({}, store.dialogSchema), {
      type: 'dialog'
    }), {
      key: 'dialog',
      data: store.dialogData,
      onConfirm: this.handleDialogConfirm,
      onClose: this.handleDialogClose,
      show: store.dialogOpen
    }));
  };
  CRUD.propsList = ['bulkActions', 'itemActions', 'mode', 'orderField', 'syncLocation', 'toolbar', 'toolbarInline', 'messages', 'value', 'options', 'multiple', 'valueField', 'defaultParams', 'bodyClassName', 'perPageAvailable', 'pageField', 'perPageField', 'totalField', 'pageDirectionField', 'hideQuickSaveBtn', 'autoJumpToTopOnPagerChange', 'interval', 'silentPolling', 'stopAutoRefreshWhen', 'stopAutoRefreshWhenModalIsOpen', 'api', 'affixHeader', 'columnsTogglable', 'placeholder', 'tableClassName', 'headerClassName', 'footerClassName',
  // 'toolbarClassName',
  'headerToolbar', 'footerToolbar', 'filterTogglable', 'filterDefaultVisible', 'autoGenerateFilter', 'syncResponse2Query', 'keepItemSelectionOnPageChange', 'labelTpl', 'labelField', 'loadDataOnce', 'loadDataOnceFetchOnFilter', 'source', 'header', 'columns', 'size', 'onChange', 'onInit', 'onSaved', 'onSave', 'onQuery', 'formStore', 'autoFillHeight', 'maxTagCount', 'overflowTagPopover', 'parsePrimitiveQuery', 'matchFunc', 'loadMoreProps'];
  CRUD.defaultProps = {
    toolbarInline: true,
    headerToolbar: ['bulkActions'],
    footerToolbar: ['statistics', 'pagination'],
    primaryField: 'id',
    syncLocation: true,
    pageField: 'page',
    perPageField: 'perPage',
    totalField: 'total',
    pageDirectionField: 'pageDir',
    hideQuickSaveBtn: false,
    autoJumpToTopOnPagerChange: true,
    silentPolling: false,
    filterTogglable: false,
    filterDefaultVisible: true,
    loadDataOnce: false,
    autoFillHeight: false,
    parsePrimitiveQuery: true,
    loadMoreProps: {
      showIcon: true,
      showText: true,
      iconType: 'loading-outline',
      contentText: {
        contentdown: '点击加载更多',
        contentrefresh: '加载中...',
        contentnomore: '没有更多数据了'
      }
    }
  };
  return CRUD;
}(React__default["default"].Component);
var CRUDRendererBase = /** @class */function (_super) {
  tslib.__extends(CRUDRendererBase, _super);
  function CRUDRendererBase(props, context) {
    var _this = _super.call(this, props) || this;
    var scoped = context;
    scoped.registerComponent(_this);
    return _this;
  }
  CRUDRendererBase.prototype.componentWillUnmount = function () {
    _super.prototype.componentWillUnmount.call(this);
    var scoped = this.context;
    scoped.unRegisterComponent(this);
  };
  CRUDRendererBase.prototype.reload = function (subpath, query, ctx, silent, replace, args) {
    var _a;
    var scoped = this.context;
    if ((args === null || args === void 0 ? void 0 : args.index) || (args === null || args === void 0 ? void 0 : args.condition)) {
      // 局部刷新
      // 由内容组件去实现
      return (_a = this.control) === null || _a === void 0 ? void 0 : _a.reload('', query, ctx, undefined, undefined, args);
    } else if (subpath) {
      return scoped.reload(query ? "".concat(subpath, "?").concat(amisCore.qsstringify(query)) : subpath, ctx);
    }
    return _super.prototype.reload.call(this, subpath, query, ctx, silent, replace, args);
  };
  CRUDRendererBase.prototype.receive = function (values, subPath, replace, resetPage, clearSelection) {
    return tslib.__awaiter(this, void 0, void 0, function () {
      var scoped;
      return tslib.__generator(this, function (_a) {
        scoped = this.context;
        if (subPath) {
          return [2 /*return*/, scoped.send(subPath, values)];
        }
        return [2 /*return*/, _super.prototype.receive.call(this, values, undefined, replace, resetPage, clearSelection)];
      });
    });
  };
  CRUDRendererBase.prototype.reloadTarget = function (target, data) {
    var scoped = this.context;
    scoped.reload(target, data);
  };
  CRUDRendererBase.prototype.closeTarget = function (target) {
    var scoped = this.context;
    scoped.close(target);
  };
  CRUDRendererBase.prototype.setData = function (values, replace, index, condition) {
    var _a, _b, _c;
    return tslib.__awaiter(this, void 0, void 0, function () {
      var store, total, items;
      return tslib.__generator(this, function (_d) {
        store = this.props.store;
        if (index !== undefined || condition !== undefined) {
          return [2 /*return*/, (_b = (_a = this.control) === null || _a === void 0 ? void 0 : _a.setData) === null || _b === void 0 ? void 0 : _b.call(_a, values, replace, index, condition)];
        } else {
          total = (values === null || values === void 0 ? void 0 : values.total) || (values === null || values === void 0 ? void 0 : values.count);
          items = (_c = values.rows) !== null && _c !== void 0 ? _c : values.items;
          if (total !== undefined) {
            store.updateTotal(parseInt(total, 10));
          }
          return [2 /*return*/, store.updateData(tslib.__assign(tslib.__assign({}, values), items ? {
            items: items
          } : {}),
          // 做个兼容
          undefined, replace)];
        }
        return [2 /*return*/];
      });
    });
  };
  CRUDRendererBase.prototype.getData = function () {
    var _a = this.props,
      store = _a.store,
      data = _a.data;
    return store.getData(data);
  };
  CRUDRendererBase.contextType = amisCore.ScopedContext;
  return CRUDRendererBase;
}(CRUD);
var CRUDRenderer = /** @class */function (_super) {
  tslib.__extends(CRUDRenderer, _super);
  function CRUDRenderer() {
    return _super !== null && _super.apply(this, arguments) || this;
  }
  CRUDRenderer = tslib.__decorate([amisCore.Renderer({
    type: 'crud',
    storeType: amisCore.CRUDStore.name,
    isolateScope: true
  })], CRUDRenderer);
  return CRUDRenderer;
}(CRUDRendererBase);

exports.CRUDRenderer = CRUDRenderer;
exports.CRUDRendererBase = CRUDRendererBase;
exports["default"] = CRUD;
